export default {
    socket: null,
    userid:'',
    message:'',
    open: function openSocket(userid) {
        this.userid = userid;
        if(typeof(WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        }
        else{
            console.log("您的浏览器支持WebSocket");
            var socketUrl="http://124.222.162.206:8190/message/imserver/"+this.userid;
            socketUrl=socketUrl.replace("https","ws").replace("http","ws");
            console.log(socketUrl);
            if(this.socket!=null){
                this.socket.close();
                this.socket=null;
            }
            this.socket = new WebSocket(socketUrl);
            //打开事件
            this.socket.onopen = function() {
                console.log("websocket已打开");
                //socket.send("这是来自客户端的消息" + location.href + new Date());
            };
            //获得消息事件
            this.socket.onmessage = function(msg) {
                console.log(msg.data);
                //发现消息进入    开始处理前端触发逻辑
                this.$message.success(msg.data)
            };
            //关闭事件
            this.socket.onclose = function() {
                console.log("websocket已关闭");
            };
            //发生了错误事件
            this.socket.onerror = function() {
                console.log("websocket发生了错误");
            }
        }
    },
    sendMessage: function sendMessage(message) {
        this.message = message
        if(typeof(WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        }else {
            console.log("您的浏览器支持WebSocket");
            console.log('{"toUserId":"'+this.userid+'","contentText":"'+this.message+'"}');
            this.socket.send('{"toUserId":"'+this.userid+'","contentText":"'+this.message+'"}');
        }
    }
}
